<template>
    <div ref="chart" style="width: 100%; height: 300px;"></div>
  </template>
  
  <script>
  import * as echarts from 'echarts';
  
  export default {
    data() {
      return {
        // Data related to the chart can be managed here if needed
      };
    },
    mounted() {
      this.initChart();
      this.startDataUpdate(); // Start updating data after chart initialization
    },
    methods: {
      initChart() {
        // Initialize echarts instance
        this.myChart = echarts.init(this.$refs.chart);
  
        // Initial option setup (can be empty if initial data is generated later)
        const option = {
          title: {
            text: 'Real-time Data',
            left: 10
          },
          xAxis: {
            type: 'category',
            data: [],
            axisLabel: {
              interval: 0,
              rotate: 45
            },
            silent: false,
            splitLine: {
              show: false
            },
            splitArea: {
              show: false
            }
          },
          yAxis: {
            splitArea: {
              show: false
            }
          },
          series: [{
            type: 'bar',
            data: [],
            large: true
          }]
        };
  
        // Set initial option
        this.myChart.setOption(option);
      },
      startDataUpdate() {
        // Update data every 5 seconds (example interval)
        setInterval(() => {
          this.updateData();
        }, 5000); // Interval in milliseconds
      },
      updateData() {
        const dataCount = 24; // Number of hours
        const data = this.generateData(dataCount); // Generate new data
        
        // Update xAxis and series data
        let option = this.myChart.getOption();
        option.xAxis[0].data = data.categoryData;
        option.series[0].data = data.valueData;
        
        // Update chart with new options
        this.myChart.setOption(option);
      },
      generateData(count) {
        const baseValue = Math.random() * 1000;
        const startTime = +new Date(2011, 0, 1); // Start time
        const categoryData = [];
        const valueData = [];
        
        for (let i = 0; i < count; i++) {
          const time = new Date(startTime + i * 3600 * 1000); // Increment by 1 hour (3600 seconds)
          const formattedTime = echarts.format.formatTime('hh:mm', time); // Format time as hh:mm
          categoryData.push(formattedTime);
          // Simulate data value
          const randomValue = baseValue + Math.random() * 500 - 250;
          valueData.push(randomValue.toFixed(2));
        }
        
        return {
          categoryData: categoryData,
          valueData: valueData
        };
      }
    }
  };
  </script>